package com.fulu.javabase.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 反射练习
 */
public class ReflectionTest {

    public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        // 通过全限定名得到class对象
        Class<?> clazz = Class.forName("com.fulu.javabase.reflection.Person");
        // 反射私有构造方法
        Constructor<?> declaredConstructor = clazz.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);
        Person person = (Person) declaredConstructor.newInstance();
        System.out.println(person.getName("a"));

        // 反射私有方法
        Method getPrivateName = clazz.getDeclaredMethod("getPrivateName", String.class);
        getPrivateName.setAccessible(true);
        System.out.println(getPrivateName.invoke(person, "b"));

        // 反射私有属性
        Field field = clazz.getDeclaredField("map");
        field.setAccessible(true);
        System.out.println(field.get(person));
    }
}
